package cn.iocoder.yudao.module.system.controller.admin.partner;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.promotion.api.coupon.CouponTemplateApi;
import cn.iocoder.yudao.module.promotion.api.coupon.dto.CouponTemplateRespDTO;
import cn.iocoder.yudao.module.system.api.partner.dto.PartnerSendReqDTO;
import cn.iocoder.yudao.module.system.controller.admin.partner.vo.PartnerPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.partner.vo.PartnerRespVO;
import cn.iocoder.yudao.module.system.controller.admin.partner.vo.PartnerSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.partnercoupon.vo.PartnerCouponPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.partnercoupon.vo.PartnerCouponRespVO;
import cn.iocoder.yudao.module.system.controller.admin.partnerstore.vo.PartnerStorePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.partnerstore.vo.PartnerStoreRespVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserUpdateStatusReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.partner.PartnerDO;
import cn.iocoder.yudao.module.system.dal.dataobject.partnercoupon.PartnerCouponDO;
import cn.iocoder.yudao.module.system.dal.dataobject.partnerstore.PartnerStoreDO;
import cn.iocoder.yudao.module.system.service.partner.PartnerService;
import cn.iocoder.yudao.module.system.service.partnercoupon.PartnerCouponService;
import cn.iocoder.yudao.module.system.service.partnerstore.PartnerStoreService;
import cn.iocoder.yudao.module.trade.api.store.StoreApi;
import cn.iocoder.yudao.module.trade.api.store.dto.StoreRespDTO;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 合伙人")
@RestController
@RequestMapping("/system/partner")
@Validated
public class PartnerController {

    @Resource
    private PartnerService partnerService;
    @Resource
    private PartnerStoreService partnerStoreService;
    @Resource
    private PartnerCouponService partnerCouponService;
    @Resource
    private StoreApi storeApi;
    @Resource
    private CouponTemplateApi couponTemplateApi;

    @PostMapping("/create")
    @Operation(summary = "创建合伙人")
//    @PreAuthorize("@ss.hasPermission('system:partner:create')")
    public CommonResult<Long> createPartner(@Valid @RequestBody PartnerSaveReqVO createReqVO) {
        Long partnerId = partnerService.createPartner(createReqVO);
        PartnerSendReqDTO reqDTO = new PartnerSendReqDTO();
        reqDTO.setPartnerIds(CollUtil.toList(partnerId));
        partnerService.sendPartnerCoupon(reqDTO);
        return success(partnerId);
    }

    @PutMapping("/update")
    @Operation(summary = "更新合伙人")
//    @PreAuthorize("@ss.hasPermission('system:partner:update')")
    public CommonResult<Boolean> updatePartner(@Valid @RequestBody PartnerSaveReqVO updateReqVO) {
        partnerService.updatePartner(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除合伙人")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('system:partner:delete')")
    public CommonResult<Boolean> deletePartner(@RequestParam("id") Long id) {
        partnerService.deletePartner(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得合伙人")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('system:partner:query')")
    public CommonResult<PartnerRespVO> getPartner(@RequestParam("id") Long id) {
        PartnerDO partner = partnerService.getPartner(id);
        PartnerRespVO partnerRespVO = BeanUtils.toBean(partner, PartnerRespVO.class);
        PartnerStorePageReqVO storePageReqVO = new PartnerStorePageReqVO();
        storePageReqVO.setPageSize(20);
        storePageReqVO.setPartnerId(id);
        PageResult<PartnerStoreDO> partnerStorePageVo = partnerStoreService.getPartnerStorePage(storePageReqVO);
        if (!CollectionUtils.isAnyEmpty(partnerStorePageVo.getList())) {
            List<PartnerStoreDO> partnerStoreList = partnerStorePageVo.getList();
            List<PartnerStoreRespVO> storeVOList = BeanUtils.toBean(partnerStoreList, PartnerStoreRespVO.class);
            List<StoreRespDTO> storeList = storeApi.getStoreList(convertSet(storeVOList, PartnerStoreRespVO::getStoreId));
            Map<Long, StoreRespDTO> storeMap = convertMap(storeList, StoreRespDTO::getId);
            storeVOList.forEach(item -> {
                if (item.getStoreId() != null && storeMap.get(item.getStoreId()) != null) {
                    item.setStoreName(storeMap.get(item.getStoreId()).getName());
                    item.setStoreType(storeMap.get(item.getStoreId()).getStoreType());
                }
                if (2 == item.getPartnerType()) {
                    item.setReferrerType(null);
                    item.setReferrerProfitRate(null);
                }
            });
            partnerRespVO.setStoreList(storeVOList);
        }

        PartnerCouponPageReqVO couponPageReqVO = new PartnerCouponPageReqVO();
        couponPageReqVO.setPageSize(20);
        couponPageReqVO.setPartnerId(id);
        PageResult<PartnerCouponDO> partnerCouponPageVo = partnerCouponService.getPartnerCouponPage(couponPageReqVO);
        if (!CollectionUtils.isAnyEmpty(partnerCouponPageVo.getList())) {
            List<PartnerCouponDO> partnerCouponList = partnerCouponPageVo.getList();
            List<PartnerCouponRespVO> couponVOList = BeanUtils.toBean(partnerCouponList, PartnerCouponRespVO.class);
            List<CouponTemplateRespDTO> couponTemplateList = couponTemplateApi.getCouponTemplateList(convertSet(couponVOList, PartnerCouponRespVO::getTemplateId));
            Map<Long, CouponTemplateRespDTO> couponTemplateMap = convertMap(couponTemplateList, CouponTemplateRespDTO::getId);
            couponVOList.forEach(item -> {
                if (item.getTemplateId() != null && couponTemplateMap.get(item.getTemplateId()) != null)
                    item.setName(couponTemplateMap.get(item.getTemplateId()).getName());
            });
            partnerRespVO.setCouponList(couponVOList);
        }
        return success(partnerRespVO);
    }

    @PutMapping("/update-status")
    @Operation(summary = "修改合伙人状态")
//    @PreAuthorize("@ss.hasPermission('system:partner:update')")
    public CommonResult<Boolean> updateStatus(@Valid @RequestBody UserUpdateStatusReqVO reqVO) {
        partnerService.updateStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @GetMapping("/page")
    @Operation(summary = "获得合伙人分页")
//    @PreAuthorize("@ss.hasPermission('system:partner:query')")
    public CommonResult<PageResult<PartnerRespVO>> getPartnerPage(@Valid PartnerPageReqVO pageReqVO) {
        PageResult<PartnerDO> pageResult = partnerService.getPartnerPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, PartnerRespVO.class));
    }

    @GetMapping("/getLpList")
    @Operation(summary = "获得LP合伙人列表")
    public CommonResult<List<PartnerRespVO>> getLpList() {
        List<PartnerDO> dataList = partnerService.getLpList();
        return success(BeanUtils.toBean(dataList, PartnerRespVO.class));
    }
    ;

    @GetMapping("/export-excel")
    @Operation(summary = "导出合伙人 Excel")
//    @PreAuthorize("@ss.hasPermission('system:partner:export')")
    @OperateLog(type = EXPORT)
    public void exportPartnerExcel(@Valid PartnerPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<PartnerDO> list = partnerService.getPartnerPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "合伙人.xls", "数据", PartnerRespVO.class,
                        BeanUtils.toBean(list, PartnerRespVO.class));
    }

    @PostMapping("/sendCoupon")
    @Operation(summary = "发送合伙人人优惠券")
    public CommonResult<Integer> sendCoupon(@RequestBody PartnerSendReqDTO sendReqDTO) {
        return success(Integer.valueOf(partnerService.sendPartnerCoupon(sendReqDTO)));
    }
}